package ai.people.netmon.msgsearch.service.impl;

import ai.people.core.common.properties.elastic.ElasticSocialMediaRegisterInfoIndex;
import ai.people.netmon.framework.domain.archives.dto.ThirdPartySearchPageResponse;
import ai.people.netmon.framework.domain.searchmsg.request.InformationSearchDetailParamVO;
import ai.people.netmon.framework.domain.searchmsg.request.InformationSearchPageParamVO;
import ai.people.netmon.framework.domain.searchmsg.request.InformationSearchReqVO;
import ai.people.netmon.framework.domain.searchmsg.vo.FbListRespFieldsVO;
import ai.people.netmon.framework.domain.searchmsg.vo.InformationSearchDetailRespVO;
import ai.people.netmon.framework.domain.searchmsg.vo.InformationSearchListRespVO;
import ai.people.netmon.framework.domain.searchmsg.vo.TgListRespFieldsVO;
import ai.people.netmon.framework.model.response.PageResponse;
import ai.people.netmon.msgsearch.domain.entity.FacebookAccountRegisterInfo;
import ai.people.netmon.msgsearch.domain.entity.TelegramAccountRegisterInfo;
import ai.people.netmon.msgsearch.mapper.es.TgAccountRegisterInfoEsMapper;
import ai.people.netmon.msgsearch.mapstruct.FbInformationSearchListRespConverter;
import ai.people.netmon.msgsearch.mapstruct.TgInformationSearchListRespConverter;
import ai.people.netmon.msgsearch.service.IJxSocialMediaRegisterInfoEsSearchService;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LiGuanNan
 * @date 2022/6/28 17:32
 */
@Service
public class JxSocialMediaRegisterInfoEsSearchServiceImpl implements IJxSocialMediaRegisterInfoEsSearchService {

    @Autowired
    @Qualifier("flElasticsearchRestTemplate")
    private ElasticsearchRestTemplate flElasticsearchRestTemplate;

    @Autowired
    @Qualifier("elasticsearchRestTemplate")
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Resource
    private FbInformationSearchListRespConverter fbListRespConverter;

    @Resource
    private TgInformationSearchListRespConverter tgListRespConverter;

    @Autowired
    private TgAccountRegisterInfoEsMapper tgAccountRegisterInfoEsMapper;


    /**
     * 分页查询
     *
     * @param reqParam 要求参数
     * @return {@link PageResponse}<{@link FacebookAccountRegisterInfo}>
     */
    @Override
    public ThirdPartySearchPageResponse<InformationSearchListRespVO<FbListRespFieldsVO>> queryFbAccountPage(InformationSearchReqVO<InformationSearchPageParamVO> reqParam) {
        List<FacebookAccountRegisterInfo> socialUsers = Lists.newArrayList();
        long total=0, totalPage=1;

        InformationSearchPageParamVO paramVO = reqParam.getData();
        if(paramVO == null){
            return ThirdPartySearchPageResponse.builderEmpty();
        }

        // 创建查询对象
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        if(StringUtils.isNotBlank(paramVO.getKeyword())){
            builder.withQuery(new MultiMatchQueryBuilder(paramVO.getKeyword(), "uid", "email", "phone"));
        }
        //es分页从0开始的，而我们的系统是从1开始的，所以-1
        builder.withPageable(PageRequest.of(paramVO.getPageNo() - 1, paramVO.getPageSize()));
        NativeSearchQuery query = builder.build();

        //指定查询索引
        IndexCoordinates indexCoordinates = IndexCoordinates.of(ElasticSocialMediaRegisterInfoIndex.getIndexBySource("facebook"));

        // 调用查询接口
        SearchHits<FacebookAccountRegisterInfo> searchHits = null;
        try {
            searchHits = flElasticsearchRestTemplate.search(query, FacebookAccountRegisterInfo.class, indexCoordinates);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(searchHits != null){
            // 记录总数
            total = searchHits.getTotalHits();
            // 计算分页总数
            totalPage = (int) ((searchHits.getTotalHits() - 1) / paramVO.getPageSize() + 1);

            List<SearchHit<FacebookAccountRegisterInfo>> hits = searchHits.getSearchHits();
            if(!CollectionUtils.isEmpty(hits)){
                socialUsers  = hits.stream().map(SearchHit::getContent).collect(Collectors.toList());
            }
            return ThirdPartySearchPageResponse.builder(fbListRespConverter.infoDataList2VoList(socialUsers), total, totalPage, paramVO.getPageNo());
        }
        return ThirdPartySearchPageResponse.builderEmpty();
    }

    /**
     * 账号详情
     *
     * @param reqParam 要求参数
     * @return {@link InformationSearchDetailRespVO}<{@link FacebookAccountRegisterInfo}>
     */
    @Override
    public InformationSearchDetailRespVO<FacebookAccountRegisterInfo> fbDetail(InformationSearchReqVO<InformationSearchDetailParamVO> reqParam) {
        if(reqParam.getData() == null || reqParam.getData().getDataId() == null){
            return null;
        }
        FacebookAccountRegisterInfo detail = flElasticsearchRestTemplate.get(reqParam.getData().getDataId(), FacebookAccountRegisterInfo.class);
        if(detail != null){
            detail.setPlatform("facebook");
        }
        return InformationSearchDetailRespVO.<FacebookAccountRegisterInfo>builder().fields(detail).build();
    }

    /**
     * 查询tg帐户分页
     *
     * @param reqVo 要求参数
     * @return {@link InformationSearchListRespVO}<{@link TgListRespFieldsVO}>
     */
    @Override
    public ThirdPartySearchPageResponse<InformationSearchListRespVO<TgListRespFieldsVO>> queryTgAccountPage(InformationSearchReqVO<InformationSearchPageParamVO> reqVo) {
        List<TelegramAccountRegisterInfo> socialUsers = Lists.newArrayList();
        long total=0, totalPage=1;

        InformationSearchPageParamVO paramVO = reqVo.getData();
        if(paramVO == null){
            return ThirdPartySearchPageResponse.builderEmpty();
        }

        // 创建查询对象
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        if(StringUtils.isNotBlank(paramVO.getKeyword())){
            builder.withQuery(new MultiMatchQueryBuilder(paramVO.getKeyword(), "id", "user_name", "phone"));
        }
        //es分页从0开始的，而我们的系统是从1开始的，所以-1
        builder.withPageable(PageRequest.of(paramVO.getPageNo() - 1, paramVO.getPageSize()));
        NativeSearchQuery query = builder.build();

        //指定查询索引
        IndexCoordinates indexCoordinates = IndexCoordinates.of(ElasticSocialMediaRegisterInfoIndex.getIndexBySource("telegram"), ElasticSocialMediaRegisterInfoIndex.getIndexBySource("twitter"));

        // 调用查询接口
        SearchHits<TelegramAccountRegisterInfo> searchHits = null;
        try {
            searchHits = elasticsearchRestTemplate.search(query, TelegramAccountRegisterInfo.class, indexCoordinates);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(searchHits != null){
            // 记录总数
            total = searchHits.getTotalHits();
            // 计算分页总数
            totalPage = (int) ((searchHits.getTotalHits() - 1) / paramVO.getPageSize() + 1);

            List<SearchHit<TelegramAccountRegisterInfo>> hits = searchHits.getSearchHits();
            if(!CollectionUtils.isEmpty(hits)){
                socialUsers  = hits.stream().map(SearchHit::getContent).collect(Collectors.toList());
            }
            return ThirdPartySearchPageResponse.builder(tgListRespConverter.infoDataList2VoList(socialUsers), total, totalPage, paramVO.getPageNo());
        }
        return ThirdPartySearchPageResponse.builderEmpty();
    }

    /**
     * telegram账号详情
     *
     * @param reqParam 要求参数
     * @return {@link InformationSearchDetailRespVO}<{@link TelegramAccountRegisterInfo}>
     */
    @Override
    public InformationSearchDetailRespVO<TelegramAccountRegisterInfo> tgDetail(InformationSearchReqVO<InformationSearchDetailParamVO> reqParam) {
        if(reqParam.getData() == null || reqParam.getData().getDataId() == null){
            return null;
        }
        TelegramAccountRegisterInfo twDetail = elasticsearchRestTemplate.get(reqParam.getData().getDataId(), TelegramAccountRegisterInfo.class, IndexCoordinates.of(ElasticSocialMediaRegisterInfoIndex.getIndexBySource("twitter")));
        TelegramAccountRegisterInfo tgDetail = elasticsearchRestTemplate.get(reqParam.getData().getDataId(), TelegramAccountRegisterInfo.class, IndexCoordinates.of(ElasticSocialMediaRegisterInfoIndex.getIndexBySource("telegram")));
        return InformationSearchDetailRespVO.<TelegramAccountRegisterInfo>builder().fields(twDetail == null ? tgDetail : twDetail).build();
    }
}
